<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { listGarden } from '@/api/dashboard'
import * as echarts from 'echarts'
const navList = ref([
  { name: '种植', id: 1 },
  { name: '加工', id: 2 },
  { name: '企业', id: 3 }
])
// 创建一个响应式引用来保存DOM元素
const chartDom = ref(null)
const gardenData = ref([])
let chartInstance = null
let chartTool = null
function getData() {
  listGarden({
    pageNum: 1,
    pageSize: 1000
  }).then((res) => {
    let data = res.rows
    if (JSON.stringify(data) === JSON.stringify(gardenData.value)) {
      return
    }
    gardenData.value = res.rows
    let xAxisData = []
    let yAxisData = []
    data.forEach((item) => {
      xAxisData.push(item.name)
      yAxisData.push(item.gardenArea)
    })
    const option = {
      xAxis: [
        {
          data: xAxisData
        }
      ],
      series: [
        {
          data: yAxisData
        }
      ]
    }
    chartInstance.setOption(option)
    chartTool.clearLoop()
    chartTool = tools.loopShowTooltip(chartInstance, option, { loopSeries: true })
  })
}
// 初始化ECharts实例并设置配置项（这里以折线图为例，但可灵活替换）
onMounted(async () => {
  await nextTick() // 确保DOM已经渲染完成
  listGarden({
    pageNum: 1,
    pageSize: 1000
  }).then((res) => {
    gardenData.value = res.rows
    let data = res.rows
    let xAxisData = []
    let yAxisData = []
    data.forEach((item) => {
      xAxisData.push(item.name)
      yAxisData.push(item.gardenArea)
    })
    chartInstance = echarts.init(chartDom.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(1, 26, 49, 0.8)',
        extraCssText: 'box-shadow: inset 0px 0px 11px 0px rgba(24,144,255,0.8)',
        borderWidth: 0,
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        },
        formatter: (params) => {
          // 获取xAxis data中的数据
          let dataStr = `<div><p style="font-weight:bold;margin:0 8px 15px;color:#FFF">${params[0].name}</p></div>`
          params.forEach((item) => {
            dataStr += `<div>
          <div style="margin: 0 8px;">
            <span style="display:inline-block;margin-right:5px;width:10px;height:10px;border-radius:50%;background-color:#FFC164;"></span>
            <span style="color:#FFF">${item.seriesName}</span>
            <span style="float:right;color:#FFC164;margin-left:20px;">${item.data}亩</span>
          </div>
        </div>`
          })
          return dataStr
        }
      },
      grid: {
        x: 70,
        y: 45
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            color: '#6E7D89', //刻度线标签颜色
            fontSize: 14,
            interval: 0 //代表显示所有x轴标签显示
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLabel: {
            formatter: '{value} 亩',
            color: '#6E7D89', //刻度线标签颜色
            fontSize: 14
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          }
        }
      ],
      series: [
        {
          name: '茶园面积',
          type: 'bar',
          barWidth: '40%',
          data: yAxisData,
          label: {
            position: 'top',
            formatter: '{c} 亩',
            fontSize: 13
          },
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                //代表渐变色从正上方开始
                offset: 0, //offset范围是0~1，用于表示位置，0是指0%处的颜色
                color: '#00D0FE'
              }, //柱图渐变色
              {
                //代表渐变色从正上方开始
                offset: 0.2, //offset范围是0~1，用于表示位置，0是指0%处的颜色
                color: '#2879D4'
              }, //柱图渐变色
              {
                offset: 1, //指100%处的颜色
                color: '#2879D400'
              }
            ])
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  //代表渐变色从正上方开始
                  offset: 0, //offset范围是0~1，用于表示位置，0是指0%处的颜色
                  color: '#FFEC43'
                }, //柱图渐变色
                {
                  //代表渐变色从正上方开始
                  offset: 0.2, //offset范围是0~1，用于表示位置，0是指0%处的颜色
                  color: '#FFB800'
                }, //柱图渐变色
                {
                  offset: 1, //指100%处的颜色
                  color: '#FFD60000'
                }
              ])
            }
          }
        }
      ]
    }
    chartInstance.setOption(option)
    chartTool = tools.loopShowTooltip(chartInstance, option, { loopSeries: true })
    setInterval(() => {
      getData()
    }, import.meta.env.VITE_APP_INTERVAL)
  })
})

// 销毁ECharts实例
onUnmounted(() => {
  if (chartInstance != null && chartInstance.dispose) {
    chartInstance.dispose()
  }
})

const process = ref(null)
const plant = ref(null)
const enterprise = ref(null)
function handelClick(id) {
  if (id === 1) {
    plant.value.open()
  }
  if (id === 2) {
    process.value.open()
  }
  if (id === 3) {
    enterprise.value.open()
  }
}
</script>

<template>
  <Item-Box title="产业概况" class="left-top" :navList="navList" @click="handelClick">
    <div ref="chartDom" style="width: 100%; height: 285px"></div>
  </Item-Box>
  <Process ref="process" />
  <Enterprise ref="enterprise" />
  <Plant ref="plant" />
</template>

<style lang="scss" scoped>
.left-top {
  height: 300px;
}
</style>
